/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jFRLivroCaixa.java
 *
 * Created on 22/06/2011, 02:16:45
 */

package sgfi;

import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
import sgfi.Classes.ClassConecta;
import sgfi.Classes.ComboItem;
import sgfi.Classes.Contas;
import sgfi.Classes.Funcoes;
import sgfi.Classes.LivroCaixa;

/**
 *
 * @author LKFalcao
 */
public class jFRLivroCaixa extends javax.swing.JFrame {

    /** Creates new form jFRLivroCaixa */
    public jFRLivroCaixa() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        codContajComboBox = new javax.swing.JComboBox();
        todasjCheckBox = new javax.swing.JCheckBox();
        consultarContajButton = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        datInijFormattedTextField = new javax.swing.JFormattedTextField();
        jLabel9 = new javax.swing.JLabel();
        datFinjFormattedTextField = new javax.swing.JFormattedTextField();
        visualizarjButton = new javax.swing.JButton();
        sairjButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setName("jLabel6"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sgfi.SGFIApp.class).getContext().getResourceMap(jFRLivroCaixa.class);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("jPanel1.border.titleColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        codContajComboBox.setName("codContajComboBox"); // NOI18N

        todasjCheckBox.setText(resourceMap.getString("todasjCheckBox.text")); // NOI18N
        todasjCheckBox.setName("todasjCheckBox"); // NOI18N

        consultarContajButton.setIcon(resourceMap.getIcon("consultarContajButton.icon")); // NOI18N
        consultarContajButton.setName("consultarContajButton"); // NOI18N
        consultarContajButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultarContajButtonActionPerformed(evt);
            }
        });

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        datInijFormattedTextField.setFormatterFactory(Funcoes.setFormatoData());
        datInijFormattedTextField.setName("datInijFormattedTextField"); // NOI18N

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        datFinjFormattedTextField.setFormatterFactory(Funcoes.setFormatoData());
        datFinjFormattedTextField.setName("datFinjFormattedTextField"); // NOI18N

        visualizarjButton.setIcon(resourceMap.getIcon("visualizarjButton.icon")); // NOI18N
        visualizarjButton.setText(resourceMap.getString("visualizarjButton.text")); // NOI18N
        visualizarjButton.setName("visualizarjButton"); // NOI18N
        visualizarjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                visualizarjButtonActionPerformed(evt);
            }
        });

        sairjButton.setIcon(resourceMap.getIcon("sairjButton.icon")); // NOI18N
        sairjButton.setText(resourceMap.getString("sairjButton.text")); // NOI18N
        sairjButton.setName("sairjButton"); // NOI18N
        sairjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sairjButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(todasjCheckBox))
                            .addComponent(codContajComboBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(consultarContajButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addGap(80, 80, 80)
                        .addComponent(jLabel9))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(visualizarjButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(datInijFormattedTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(datFinjFormattedTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                            .addComponent(sairjButton))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(consultarContajButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(todasjCheckBox))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(codContajComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(datInijFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(datFinjFormattedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(visualizarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sairjButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {sairjButton, visualizarjButton});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(285, 285, 285)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    ClassConecta conexao = new ClassConecta();
    public double saldoAnterior;
    public double saldoDisponivel;

    private void consultarContajButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultarContajButtonActionPerformed
        // TODO add your handling code here:
        try {
            Contas oConta = new Contas();
            ResultSet rs = null;
            try {
                rs = oConta.getConsultarContas();
            } catch (SQLException ex) {
                Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
            }

            codContajComboBox.removeAllItems();
            while (rs.next()) {
                codContajComboBox.addItem(new ComboItem(rs.getInt(1), rs.getString("Banco")));
            }
            codContajComboBox.updateUI();
        } catch (SQLException ex) {
            Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_consultarContajButtonActionPerformed

    private void visualizarjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_visualizarjButtonActionPerformed
        // TODO add your handling code here:
        try {
            /* Preenche o relatório com os dados. Gera o arquivo .jrprint */
            LivroCaixa oLivro = new LivroCaixa();

            ComboItem comboConta = (ComboItem) codContajComboBox.getSelectedItem();
            if (!todasjCheckBox.isSelected()) {
                oLivro.setCodConta(comboConta.getId());
            }
            //definir datas
            SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
            oLivro.setDataLanc((Date) formato.parse(datInijFormattedTextField.getValue().toString()));
            oLivro.setDatFinal((Date) formato.parse(datFinjFormattedTextField.getValue().toString()));

            if (saldoAnterior == 0) {
                try {
                    saldoAnterior = oLivro.getConsultarSaldo("anterior",conexao);
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(null, ex, "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
                    Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            if (saldoDisponivel == 0) {
                try {
                    saldoDisponivel = oLivro.getConsultarSaldo("saldo", conexao) + oLivro.getConsultarSaldo("anterior", conexao);
                } catch (SQLException ex) {
                    Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            String caminhoRelJasper = "resources/rLivroCaixa.jasper";

            ResultSet rs;
            rs = oLivro.getConsultar();

            JRResultSetDataSource ds = new JRResultSetDataSource(rs);
            Map parametros = new HashMap();
            parametros.put("saldoAnterior", saldoAnterior);
            parametros.put("saldoDisponivel", saldoDisponivel);
            URL arquivo = getClass().getResource(caminhoRelJasper);
            if (arquivo == null) {
                JOptionPane.showMessageDialog(null, "Arquivo jasper não encontrado");
            }
            JasperReport report;
            report = JasperManager.loadReport(arquivo.openStream());
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, parametros, ds);
            JasperViewer jrviewer = new JasperViewer(jasperPrint, false);
            jrviewer.setVisible(true);

        } catch (IOException ex) {
            Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JRException ex) {
            Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (java.text.ParseException ex) {
            Logger.getLogger(jFRLivroCaixa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_visualizarjButtonActionPerformed

    private void sairjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sairjButtonActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_sairjButtonActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        //Conectar ao banco de dados
        ClassConecta.conecta();
        //Centralizar tela
        setLocationRelativeTo(null);
        consultarContajButtonActionPerformed(null);
        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
        Date datLanc = new Date();
        String datAtual = null;
        Calendar calendar = Calendar.getInstance();
        datLanc = calendar.getTime();
        datAtual = formato.format(datLanc);
        datInijFormattedTextField.setValue(datAtual );
        datFinjFormattedTextField.setValue(datAtual );
    }//GEN-LAST:event_formWindowOpened

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jFRLivroCaixa().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox codContajComboBox;
    private javax.swing.JButton consultarContajButton;
    private javax.swing.JFormattedTextField datFinjFormattedTextField;
    private javax.swing.JFormattedTextField datInijFormattedTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton sairjButton;
    private javax.swing.JCheckBox todasjCheckBox;
    private javax.swing.JButton visualizarjButton;
    // End of variables declaration//GEN-END:variables

}
